package com.doge.calcalbum.core

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.doge.calcalbum.R
import com.doge.calcalbum.utils.log

open class BaseDialogFragment : DialogFragment() {
    private val classSimpleName by lazy { javaClass.simpleName }
    open val hasShadow: Boolean = false
    open val cancelable: Boolean = true

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return Dialog(
            requireActivity(),
            if (hasShadow) R.style.Theme_Light_NoTitle_Dialog else R.style.Theme_Light_NoTitle_NoShadow_Dialog
        ).apply {
            setCanceledOnTouchOutside(cancelable)
            window?.let(::setWindow)
        }
    }

    fun show(fragmentManager: FragmentManager?) {
        when {
            fragmentManager == null -> log("fragmentManager is detach after parent destroy")
            fragmentManager.isStateSaved -> log("dialog fragment show when fragmentManager isStateSaved")
            else -> show(fragmentManager, classSimpleName)
        }
    }

    open fun setWindow(win: Window) {
        win.setWindowAnimations(R.style.Animation_Bottom_Rising)
        win.decorView.setPadding(0, 0, 0, 0)
        val lp = win.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        win.attributes = lp
        win.setGravity(Gravity.BOTTOM)
    }

}